﻿using System;
using ASPNETVN.PORTAL.Components.Helpers;
using ASPNETVN.PORTAL.Components.Security;
using ASPNETVN.PORTAL.Components.UI;
using ASPNETVN.PORTAL.Modules.QuickDownload.Components;

namespace ASPNETVN.PORTAL.Modules.QuickDownload.Controls
{
    public partial class AddEditDocument : AddEditItemControl
    {
        protected override void OnInit(EventArgs e)
        {
            this.ButtonUpdate = btnUpdate;
            this.ButtonCancel = btnCancel;

            this.Update += new EventHandler(AddEditDocument_Update);
            base.OnInit(e);
        }

        void AddEditDocument_Update(object sender, EventArgs e)
        {
            // Lưu thông tin vào CSDL.

            Components.Item document = new Components.Item();
            if (this.ItemID > 0)
            {
                document = Components.Item.Load(this.ItemID);
            }

            document.ModuleID = this.ModuleID;
            document.Category = this.txtCategory.Text;
            document.Title = this.txtTitle.Text;
            document.Description = this.txtDescription.Text;
            //document.CreatedBy = PortalSecurity.CurrentUser.Identity.Email;
            
            if (this.ItemID == 0)
            {
                document.CreatedBy = PortalSecurity.CurrentUser.Identity.Email;
                document.CreatedDate = DateTime.Now;
                this.ItemID = document.Insert();
            }
            else
            {
                document.ID = this.ItemID;
                document.Update();
            }
            string url = HttpUrlBuilder.BuildAddEditUrl(this.ModuleID, this.ItemID, "UploadDocument", "");
            Response.Redirect(url);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack == false)
            {
                if (this.ItemID > 0)
                {
                    Item document = Item.Load(this.ItemID);
                    if (document != null)
                    {
                        txtCategory.Text = document.Category;
                        txtTitle.Text = document.Title;
                        txtDescription.Text = document.Description;
                        btnUpload.Enabled = true;
                    }
                }
                else
                {
                    btnUpload.Enabled = false;
                }
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            string url = HttpUrlBuilder.BuildAddEditUrl(this.ModuleID, this.ItemID, "UploadDocument", "");
            Response.Redirect(url);
        }
    }
}